<template>
    <div class="addnsxx">
        <el-form ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px" size="small">
            <el-form-item :label="stagesItem.stageName" prop="">
                <el-tag v-for="tag in lists" :key="tag.stageTaskId" size="large" closable @close="handleClose(tag)">
                    {{ tag.taskName }}
                </el-tag>
            </el-form-item>
            <el-form-item label="农事事项" prop="userName">
                <el-input v-model="formdata.taskName" placeholder="请输入农事事项"/>
            </el-form-item>
            <el-form-item label="">
                <el-button size="small" type="primary" @click="confirm">确 定</el-button>
                <el-button size="small" @click="close">取 消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import { ref,onMounted,reactive} from 'vue';
import {getTaskList,addTask,delTask} from '@/api/plant'

import { message } from '@/utils/element'
import { ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'

const props = defineProps({
    stagesItem: {
        type:Object,
        default:{}
    },
})
const emit = defineEmits(['close'])
const userStore = useUserStore()

const formdata = ref({})
const ruleFormRef = ref(null)
const lists = ref([])
const rules = reactive({
    taskName:[
        { required: true, message: '请输入农事事项', trigger: 'blur' },
    ],
})
onMounted(async ()=>{
    // 获取种植阶段下的事项（任务）
    get_task_list()
})

const get_task_list = async()=>{
    const res = await getTaskList({ page: 1, limit: 100,stageId:props.stagesItem.stageId})
    if (res.code == 0) {
        lists.value = res.data
    }
}

const close=()=>{
    emit('close') 
}

const confirm = async ()=>{
    if(!formdata.value.taskName){
        return message('请输入农事事项',3)
    }
    const res = await addTask({
        "companyId": props.stagesItem.companyId,
        "farmId": props.stagesItem.farmId,
        "stageId": props.stagesItem.stageId,
        "taskName": formdata.value.taskName
    })
    if(res.code ==0 || res.success){
        formdata.value.taskName = ''
        get_task_list()
    }else{
        message(res.message,3)
    }
}

const handleClose = async (item)=>{
    console.log("item",item)
    ElMessageBox.confirm('确认删除吗?','提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const res = await delTask([item.stageTaskId])
        if(res.code ==0  || res.success){
            get_task_list()
        }else{
            message(res.message,3)
        }
    })
}

</script>
<style lang="scss">
.addnsxx{
    .el-tag{
        margin-right: 10px;
        margin-bottom: 10px;
    }
}
</style>
